// 单文件上传
/**
 * @param {Function} onChange 选择文件变化时的回调函数
 * @param {Function} onFail 上传失败后回调
 * @param {?Number} fileSize 可选，上传的文件大小限制（单位M）
 * @param {?Array} fileTypeList 可选，上传的文件类型 ['jpg','jpeg','gif']
 */

import React from 'react';
import styles from './index.module.less';
import { SUCCESS_CODE } from '@/services/constant';
import { UploadFile } from '@/services/index';
import { FILE_TYPE_LIST } from './constants';
import { Toast } from 'antd-mobile-v2';

export default class UploadInput extends React.Component<any, any> {
  fileInputRef: any;
  constructor(props) {
    super(props);
    this.state = {
    };
  }

  // 处理符合条件的文件
  dealFileFn = (e) => {
    if (!e.target.value) { return Toast.info('未选取文件'); }
    const size = this.getFileSize(e);
    if (!size) {
      this.clearInputValueFn();
      return;
    }
    const files = e.target.files;
    this.addFile(files, 'add');
  }

  // 检查文件是否符合要求
  getFileSize = (e) => {
    let size: any = 0;
    const files = e.target.files;
    const { fileSize = 10, fileTypeList = [...FILE_TYPE_LIST] } = this.props;
    for (let index = 0; index < files.length; index++) {
      const file = e.target.files[index];
      const fileName = files[index].name.match(/\.([0-9,a-z,A-Z]+)$/)?.[1].toLocaleLowerCase();
      size += file.size;
      if (fileTypeList.indexOf(fileName) === -1) { // 检查文件格式
        Toast.info('文件上传类型不符合要求');
        return;
      }
    }
    if (fileSize < parseInt(size) / 1024 / 1024) {
      Toast.info(`上传文件大小不能大于${fileSize}M`);
      return;
    }
    return size;
  }

  // 清空input的值
  clearInputValueFn = () => {
    if (this.fileInputRef) {
      this.fileInputRef.value = '';
    }
  }

  // 点击上传
  addFile = async (files: any, type: string) => {
    if (type == 'add') {
      this.uploadImage(files);
    }
  };

  // 文件上传
  uploadImage = async (files) => {
    const { onChange, onFail } = this.props;
    const formData = new FormData();
    formData.append('file', files[0]);
    formData.append('fileType', '1');
    formData.append('device', 'H5');
    // 只能单文件上传接口
    Toast.loading('处理中', 0, null, true);
    const res = await UploadFile(formData);

    console.log('res--------:',res);

    // fileId: "bea5cf96cc3944f2b69d943848323594"
    // fileName: "b07fb89940934e3596a6d6431af815aa.jpg"
    // fileOriginName: "cache-loader.jpg"
    // filePath: ""
    // fileUrl: "identity/20210811/b07fb89940934e3596a6d6431af815aa.jpg"


    // form表单直接获取的文件信息格式
    if (res.status === SUCCESS_CODE) {
      Toast.hide();
      const current = {
        id: res.data.id || res.data.fileId,
        url: res.data.url || res.data.fileUrl,
        name: res.data.originName || res.data.fileOriginName,
        fileSize: res.data.fileSize
      };
      onChange(current);
      this.clearInputValueFn();
    } else {
      Toast.hide();
      this.clearInputValueFn();
      onFail && onFail();
    }
  };


  render() {
    return (
      <div className={styles.wrap}>
        <input
          ref={(el) => this.fileInputRef = el}
          className={styles.inputBOX}
          // multiple
          type="file"
          // accept={accept}
          name="上传文件"
          onChange={(e) => this.dealFileFn(e)}
        />
      </div>
    );
  }
}